<!--
 * @Author: lide1202@hotmail.com
 * @Date: 2021-4-6 11:04:24
 * @Last Modified by:   lide1202@hotmail.com
 * @Last Modified time: 2021-3-13 11:04:24
 !-->
<template>
  <el-form label-width="80px" label-position="left">
    <el-form-item v-for="(item, index) in options" :key="index" :label="item.label" :prop="item.name" :required="item.required">
      <el-input-number v-if="item.type == 'el-input-number'" v-model="formData[item.name]" controls-position="right" :placeholder="item.placeholder" @change="changed($event, item.name)" />

      <el-input v-if="item.type == 'el-input-text'" v-model.trim="formData[item.name]" type="text" placeholder="请输入内容" clearable @change="changed($event, item.name)" />

      <el-input v-if="item.type == 'el-input-textarea'" v-model.trim="formData[item.name]" type="textarea" rows="2" placeholder="请输入内容" @change="change($event, item.name)" />

      <el-switch v-if="item.type == 'el-switch'" v-model="formData[item.name]" placeholder="请输入内容" @change="changed($event, item.name)" />

      <ColorPicker v-if="item.type == 'vue-color'" v-model="formData[item.name]" @change="(val) => changed(val, item.name)" />

      <el-upload v-if="item.type == 'el-upload-picture'" action="https://jsonplaceholder.typicode.com/posts/" list-type="picture-card" />

      <el-radio-group v-if="item.type == 'el-radio-group'" v-model="formData[item.name]" @change="(val) => changed(val, item.name)">
        <el-radio label="本窗口" />
        <el-radio label="新窗口" />
      </el-radio-group>

      <el-select v-if="item.type == 'el-select'" v-model="formData[item.name]" placeholder="请选择" @change="(val) => changed(val, item.name)">
        <el-option label="区域一" value="shanghai" />
        <el-option label="区域二" value="beijing" />
      </el-select>

      <el-slider v-if="item.type == 'el-slider'" v-model="formData[item.name]" />
    </el-form-item>
  </el-form>
</template>

<script>
import ColorPicker from './colorPicker.vue'
export default {
  name: 'DynamicForm',
  components: {
    ColorPicker,
  },
  model: {
    prop: 'value',
    event: 'input',
  },
  props: {
    options: Array,
    value: {
      type: [Object],
      default: () => {},
    },
  },
  data() {
    return {
      formData: {},
    }
  },
  watch: {
    value(newValue, oldValue) {
      this.formData = newValue || {}
    },
  },
  mounted() {},
  methods: {
    // 无论哪个输入框改变 都需要触发事件 将值回传
    changed(val, key) {
      if (val.extend) {
        this.$set(this.formData, key, val.value)
      } else {
        this.$set(this.formData, key, val)
      }
      this.$emit('onChanged', this.formData)
    },
  },
}
</script>

<style scoped lang="scss">
/deep/ .el-form-item__label {
  font-size: 12px;
  color: #fff;
}
</style>
